package com.usian.skill.config;

import com.alibaba.fastjson.JSON;
import com.usian.skill.mapper.GoodsMapper;
import com.usian.skill.vo.GoodsVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Component
public class InitRedis {
    @Resource
    private GoodsMapper goodsMapper;
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @PostConstruct
    public void reload(){
        List<GoodsVo> goodsVoList = goodsMapper.findAll();
        if(!CollectionUtils.isEmpty(goodsVoList)){//存在值
            for (GoodsVo vo:goodsVoList) {
                //将商品的信息按照id依次保存
                stringRedisTemplate.opsForValue().set(vo.getId().toString(), JSON.toJSONString(vo));
            }
            //将所有的商品信息保存在Redis
            stringRedisTemplate.opsForValue().set("goods",JSON.toJSONString(goodsVoList));
        }
    }
}
